package com.itcast.tcp.server;

import com.itcast.tcp.client.encoder_tcp.TcpPackageEncoder;
import com.itcast.tcp.server.decoder_tcp.TcpPackageDecoder;
import com.itcast.tcp.server.handler.ServerTcpPackageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 10:59
 **/
public class NettyTcpPackageServer {
    public static void main(String[] args) {
        //监控客户端连接的主线程
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        
        //处理已经连接的客户端请求,默认线程池大小cpu*2
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            
            //创建server的主线程
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            
            //绑定两个监控线程池
            serverBootstrap.group(bossGroup, workerGroup);
            
            //绑定服务端需要使用的channel类型
            serverBootstrap.channel(NioServerSocketChannel.class);
            
            //进行pipeline的绑定,并在pipeline中加入channelhandler
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    
                    socketChannel.pipeline()
                            .addLast(new TcpPackageEncoder())
                            .addLast(new TcpPackageDecoder())
                            .addLast(new ServerTcpPackageHandler())
                    ;
                }
            });
            
            //绑定监听端口
            ChannelFuture future = serverBootstrap.bind(8080).sync();
            System.out.println("服务器启动成功!");
            
            //监听channel的关闭请求
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
